/**
 * Copyright (c) 2009, Jacek Karczmarczyk
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * - Neither the name of the author nor the names of its contributors may be
 *   used to endorse or promote products derived from this software without
 *   specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * @package Larchana_Javascript
 * @version 0.1
 * @author Jacek Karczmarczyk <jacek@karczmarczyk.pl>
 */

/**
 * Example usage:
 *
 * <form id="someform" data-handler="showResponse">...</form>
 *
 * <script type="javascript">
 *   $('#someform').larchanaAjaxForm({
 *     showResponse: function (message) { 
 *       alert("The response is: " + message); 
 *     }
 *   });
 * </script>
 *
 *
 * Or:
 *
 * <form id="someform" data-redirect="/another/page">...</form>
 *
 * <script type="javascript">
 *   $('#someform').larchanaAjaxForm();
 * </script>
 *
 *
 */

"use strict";

(function ($, window) {
	$.fn.larchanaAjaxForm = function (handlers) {
		this.each(function () {
			var i, $form = $(this), form = this;

			// Create the default submit handler (if not defined earlier)
			//
			if (typeof this.larchanaAjaxFormHandlers === 'undefined') {
				$form.submit(function () {
					$.ajax({
						type: $form.attr('method'),
						async: true,
						url: $form.attr('action'),
						data: $form.serialize(),
						complete: $.ajaxComplete(function (message) {
							if ($form.attr('data-redirect') || (form.larchanaAjaxFormHandlers[$form.attr('data-handler')] === undefined)) {
								form.larchanaAjaxFormHandlers['default'](message);
							}
							else {
								form.larchanaAjaxFormHandlers[$form.attr('data-handler')](message);
							}
						})
					});
					return false;
				});

				this.larchanaAjaxFormHandlers = [];
			}

			// Form uses redirector handler
			//
			if ($form.attr('data-redirect')) {
				this.larchanaAjaxFormHandlers['default'] = function () {
					window.document.location = $form.attr('data-redirect') ? $form.attr('data-redirect') : window.document.location;
				};
			}
			// Apply default handler (used where data-handler is not defined or handler with this name is not defined
			//
			else if (typeof handlers === 'function') {
				this.larchanaAjaxFormHandlers['default'] = handlers;
			}
			// Default handler is not defined, use alert function and apply user defined named handlers
			//
			else {
				// Do not overwrite if default handler is already defined
				//
				if (this.larchanaAjaxFormHandlers['default'] === undefined) {
					this.larchanaAjaxFormHandlers['default'] = function (message) {
						window.alert(message);
					};
				}
				
				if (typeof handlers === 'object') {
					for (i in handlers) {
						if (typeof handlers[i] === 'function') {
							this.larchanaAjaxFormHandlers[i] = handlers[i];
						}
					}
				}
			}
		});
	};

}(jQuery, window));